package com.hhd.form.table.db;

import com.hhd.form.mapper.DBMapper;
import com.hhd.form.table.TableDefinition;
import com.hhd.form.table.field.TableFieldDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MysqlOperator implements Operator {

    @Autowired
    DBMapper dbMapper;

    @Override
    public DBType getDBType() {
        return DBType.mysql;
    }

    @Override
    public void doCreateTable(TableDefinition table) {
        dbMapper.createTableForMysql(table.getTableName(), table.getComment());
    }

    @Override
    public void updateTableComment(TableDefinition table) {
        dbMapper.updateTableCommentForMysql(table.getTableName(), table.getComment());
    }

    @Override
    public void doCreateTableField(TableFieldDefinition tableField) {
        tableField.setRealDBType(resolveRealType(tableField));
        dbMapper.createTableFieldForMysql(tableField);
    }

    @Override
    public void updateFieldComment(TableFieldDefinition tableField) {
        tableField.setRealDBType(resolveRealType(tableField));
        dbMapper.updateFieldCommentForMysql(tableField);
    }

    private String resolveRealType(TableFieldDefinition tableField) {
        switch (tableField.getDbType()) {
            case string:
                return "VARCHAR(" + tableField.getLength() + ")";
        }
        throw new RuntimeException("不支持的类型: " + tableField.getDbType());
    }
}
